var SettingNavCtrl = ['$scope', '$rootScope',
    function ($scope, $rootScope) {
        var configData = $api.getStorage('configData');
        $scope.menu_list = [
            {
                name: $rootScope.language.TIP_SETTING_ABOUT,
                url: "#setting/about",
                id: "about",
                type: "2",
                show: $rootScope.purview['\/setting\/about'].show
            }, {
                name: $rootScope.language.TIP_SETTING_SETTING,
                url: "#setting/shop_set",
                id: "shop_set",
                type: "2",
                show: $rootScope.purview['\/setting\/shop_set'].show
            }, {
                name: $rootScope.language.TIP_SETTING_CHECK,
                url: "#setting/check_set",
                id: "check_set",
                type: "2",
                show: $rootScope.user.UserCode == '000' ? 0 : 1
            }, {
                name: $rootScope.language.TIP_SETTING_MANAGER,
                url: "#setting/user_manage",
                id: "user_manage",
                type: "2",
                show: $rootScope.purview['\/setting\/user_manage'].show
            }, {
                name: $rootScope.language.TIP_SETTING_MANAGER2,
                url: "#setting/user2_manage",
                id: "user2_manage",
                type: "2",
                show: $rootScope.purview['\/setting\/user2_manage'].show
            }, {
                name: $rootScope.language.TIP_SETTING_COMMON_SET,
                url: "#setting/common_set",
                id: "common_set",
                type: "2",
                show: $rootScope.purview['\/setting\/common_set'].show
                        //show: "1"
            }, {
                name: $rootScope.language.TIP_SETTING_PRINT,
                url: "#setting/print_set",
                id: "print_set",
                type: "2",
                show: $rootScope.purview['\/setting\/print_set'].show
            }, {
                name: $rootScope.language.TIP_SETTING_DOWNLOAD,
                url: "#setting/patch",
                id: "patch",
                type: "2",
                show: $rootScope.purview['\/setting\/patch'].show
                        //show: "1"
            },
            {
                name: "定时任务", //$rootScope.language.TIP_SETTING_PRICE,
                url: "#setting/task_by_time",
                id: "task_by_time",
                type: "2",
                show: 1
            },{
                name: $rootScope.language.TIP_SETTING_NOT_UPLOAD,
                url: "#setting/wait_upload",
                id: "wait_upload",
                type: "2",
                show: $rootScope.purview['\/setting\/wait_upload'].show
            }, {
                name: $rootScope.language.TIP_SETTING_CHEN,
                url: "#setting/chen_lie",
                id: "chen_lie",
                type: "2",
//                show: $rootScope.purview['\/setting\/chen_lie'].show
                show: (configData.shanghu == 'lqx' || configData.shanghu == 'lqxtest') ? 1 : 0
            }, {
                name: $rootScope.language.TIP_SETTING_STOCK,
                url: "#setting/stock_synch",
                id: "stock_synch",
                type: "2",
                show: $rootScope.purview['\/setting\/stock_synch'].show
//				show:"1"
            }, {
                name: $rootScope.language.TIP_SETTING_PRICE,
                url: "#setting/sku_price_synch",
                id: "sku_price_synch",
                type: "2",
                show: $rootScope.purview['\/setting\/sku_price_synch'].show
            }, {
                name: $rootScope.language.TIP_SETTING_INCREMENT,
                url: "#setting/increment_module",
                id: "increment_module",
                type: "2",
                show: $rootScope.purview['\/setting\/increment_module'].show
            }, {
                name: "其他",
                url: "#test/index",
                id: "test",
                type: "2",
                show: "1"
            }];

    }];
var SettingAboutCtrl = ['$scope', '$rootScope', '$location', '$http', 'ShopSetCheck', 'BaseGoods',
    function ($scope, $rootScope, $location, $http, ShopSetCheck, BaseGoods) {

        ShopSetCheck();
        $scope.configData = $api.getStorage('configData');
        //当前二级菜单为about
        $scope.curr = 'about';
        //获取信息
        $scope.info = {
            ver: $rootScope.language.TIP_SETTING_UNGET,
            net: $rootScope.language.TIP_SETTING_UNGET,
            update_time: $rootScope.language.TIP_SETTING_UNGET,
            brand_name: $rootScope.language.TIPS_SET_BAISON_YISHANG,
            fenbianlv: $rootScope.language.TIP_SETTING_UNGET,
            deviceId: $rootScope.language.TIP_SETTING_UNGET,
            deviceModel: $rootScope.language.TIP_SETTING_UNGET
        };
        if (typeof baison_app.api !== 'undefined') {
            //$scope.info.ver = baison_app.api.appName + " " + baison_app.api.appVersion + " for " + baison_app.api.systemType + ' ' + baison_app.api.systemVersion;
            $scope.info.ver = $scope.configData.version;
            $scope.info.update_time = $scope.configData.update_time;
            $scope.info.net = baison_app.api.connectionType;
            $scope.info.fenbianlv = baison_app.api.screenWidth + 'x' + baison_app.api.screenHeight;
            $scope.info.deviceId = baison_app.api.deviceId;
            $scope.info.deviceModel = baison_app.api.deviceModel;
        }
        //升级日志
        $scope.update_log = [];
        $http.get('./install/updateLog.json').success(function (ret) {
            $scope.update_log = ret;
        });

        $scope.jumpUpdateLog = function () {
            $location.path('/setting/update_log');
        };
        //开发团队
        $scope.jumpDevTeam = function () {
            $location.path('/setting/dev_team');
        };
        //关闭
        $scope.close = function () {
            $location.path('/setting/about');
        };

        //added by lqx maowei on 20170124 清理localstorage,并检查更新，有更新就更新
        $scope.system_update = function () {
            /***added by lqx maowei on 20170502 增加时间长的情况下提示***/
            var is_response = false;
                //num_selfadd = 0;
            var mam = api.require('mam');
            mam.checkUpdate(function(ret, err) {
                if (ret) {
                    
                    var result = ret.result;
                    if (result.update == true && result.closed == false) {
                        is_response = true;
                        var str = '新版本型号:' + result.version + ';更新提示语:' + result.updateTip + ';下载地址:' + result.source + ';发布时间:' + result.time;
                        api.confirm({
                            title : '有新的版本,是否下载并安装 ',
                            msg : str,
                            buttons : ['确定', '取消']
                            //buttons : ['确定']
                        }, function(ret, err) {
                            if (ret.buttonIndex == 1) {
                                //added by lqx maowei on 20170125 清理clearstorage
                                /*$api.clearStorage();
                                var path = 'file://' + baison_app.api.fsDir + '/YsPos.db';
                                */
                                //added by lqx maowei on 20170125 删除设备本地数据库文件
                                /*
                                baison_app.fs.remove({
                                    path: path
                                }, function (ret, err) {
                                });*/
                                if (api.systemType == "android") {
                                    api.download({
                                        url : result.source,
                                        report : true
                                    }, function(ret, err) {
                                        if (ret && 0 == ret.state) {/* 下载进度 */
                                            api.toast({
                                                msg : "正在下载应用:" + ret.percent + "%",
                                                duration : 2000
                                            });
                                        }
                                        if (ret && 1 == ret.state) {/* 下载完成 */
                                            var savePath = ret.savePath;
                                            api.installApp({
                                                appUri : savePath
                                            });
                                        }
                                        if(err){
                                            api.alert({
                                                msg : "更新下载中出现问题,请重启应用再试:" + err.msg
                                            });
                                        }
                                    });
                                }
                                if (api.systemType == "ios") {
                                    api.installApp({
                                        appUri : result.source
                                    });
                                }
                            }
                            if(err){
                                api.alert({
                                    msg : "更新出现问题,请重启应用再试:" + err.msg
                                });
                            }
                        });

                    } else {
                        is_response = true;
                        api.alert({
                            msg : "暂无更新"
                        });
                    }
                }

                else{
                    api.alert({
                        msg : "更新失败:" + err.msg
                    });
                }
            });
            /*
            var interval_network_inspect = setInterval(function () {
                if(!is_response){
                    baison_app.api.toast({msg: "更新请求中,请稍等..."});
                    /*
                    num_selfadd ++;
                    if(num_selfadd > 60){
                        aison_app.api.toast({msg: "更新请求失败"});
                        clearInterval(interval_network_inspect);
                        num_selfadd = 0;
                    }*/
            /*
                }else{
                    clearInterval(interval_network_inspect);
                }
            },1000);*/

            var wait_time_out = {};
            wait_time_out = setTimeout(function () {
                clearInterval(wait_time_out);
                if(!is_response){
                    baison_app.api.toast({msg: "更新请求中...请耐心等待或者重试"}); 
                }
            }, 10000);
                
        }
        /*
        $scope.$on('$routeChangeStart', function () {
            clearInterval(interval_network_inspect);
        });*/

    }];
//店铺绑定设置
var SettingShopsetCtrl = ['$scope', '$rootScope', '$location', 'ShopGet', 'ShopSet', 'ShopSearch',
    function ($scope, $rootScope, $location, ShopGet, ShopSet, ShopSearch) {
        if ($rootScope.user.UserCode == '000') {
            $rootScope.purview['\/setting\/shop_set'] = {show: 1};
            $rootScope.purview['\/setting\/common_set'] = {show: 1};
            $rootScope.purview['\/setting\/patch'] = {show: 1};
            $rootScope.purview['\/reLogin_action'] = {show: 1};
        }
        //当前二级菜单为shop_set  设置柜台
        $scope.curr = 'shop_set';
        $scope.input_value = '';
        $scope.shop_list = [];
        $scope.ShopName = $rootScope.current_shop.ShopName;
        $scope.cas_show = true;
        var configData = $api.getStorage('configData');
        //lqx 不显示收银台设置
        if ($rootScope.purview['\/MainCtrl\/cashDeskSet'].show == 0) {
            $scope.cas_show = false;
        }
        //收银台设置
        $scope.clickToCas = function () {
            if (typeof $scope.ShopName == 'undefined') {
                baison_app.api.toast({msg: $rootScope.language.TIP_SETTING_BIND_SHOP});
                return;
            }
            $location.path('/setting/user_cash_set');
        };
        //下载数据
        $scope.download = function () {
            baison_app.api.showProgress({
                title: $rootScope.language.TIP_INDEX_DOWNLOAD,
                text: '',
                modal: false
            });
            ShopGet().then(function (ret) {
                baison_app.api.hideProgress();
                baison_app.api.toast({msg: $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY
                });
            }).catch(function (err) {
//              baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],
//                  msg: err
//              });
                baison_app.api.toast({msg: $rootScope.language.MSG_NETWORK_ABNORMAL}); //没有联网
                baison_app.api.hideProgress();
            });
        };
        //搜索数据（输入店铺代码或者店铺名字）
        $scope.search = function () {
            //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:'herere'});
            var keywords = $scope.input_value;
            ShopSearch(keywords).then(function (ret) {
                if (ret.length == 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_CANT_FOUND_RESULT
                    });
                } else {
                    $scope.shop_list = ret;
                }
            }).catch(function (err) {
                baison_app.api.toast({msg: err});
            });
        };
        //选中店铺
        $scope.select = function (shop) {
            $scope.current_shop = shop;
            $scope.curr_switch = shop;
        };
        //上传结果
        $scope.upload = function (shop) {
            if ($rootScope.current_shop === $scope.current_shop) {
                if (typeof $scope.current_shop === 'string') {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_CHOSE_SHOP
                    });
                } else {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_BINDED_SHOP
                    });
                }
            } else {
                $api.setStorage('current_shop', $scope.current_shop);
                $rootScope.current_shop = $scope.current_shop;
                $scope.ShopName = $rootScope.current_shop.ShopName;
                ShopSet().then(function (ret) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
//                        msg: ret.data.message
                        msg: $rootScope.language.TIP_INDEX_BIND_SHOP_SUCCESS
                    });
                }).catch(function (err) {
//                  baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
//                      msg: err
//                  });
                    baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
                });
            }
        }
        ;
    }
];
//设置收银台
var SettingCashCtrl = ['$scope', '$rootScope', 'ngDialog', '$location', 'shopCashDesk',
    function ($scope, $rootScope, ngDialog, $location, shopCashDesk) {
        $scope.curr = 'shop_set';
        var configData = $api.getStorage('configData');
        //获取收银台信息，并选定已选择收银台
        $scope.getCashSetData = function () {
            var param = {
                'shop_code': $rootScope.current_shop.ShopCode
            };
            shopCashDesk.getCashList(param).then(function (ret) {
                $scope.cashlist = ret.data.data.data;
                $scope.cashlist.forEach(function (n) {
                    if (configData.cashsetData.cashNum == n.cashNum) {
                        n.selected = true;
                    }
                });
            }).catch(function (err) {
                $scope.cashlist = [];
                $scope.cashlist[0] = configData.cashsetData;
                $scope.cashlist[0].selected = true;
                baison_app.api.toast({
                    msg: $rootScope.language.MSG_NETWORK_ABNORMAL
                });
            });
        };
        $scope.getCashSetData();
        //点击修改，弹出对话框
        $scope.modifyhtml = function (modify) {
            $scope.modify = modify;
            windows_modify = ngDialog.open({closeByDocument: false,
                template: './html/setting/cashset/modify.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope
            });
        };
        //取消
        $scope.cancle = function () {
            ngDialog.close(windows_modify);
        };
        //重置
        $scope.modify_reset = function (modify) {
        };
        //关闭
        $scope.close = function () {
            $location.path('/setting/shop_set');
        };
        //修改对话框中确认按钮
        $scope.cash_modify = function (data) {
            if (typeof data.cashName == "undefined" || data.cashName == "") {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_CASHIER_DESK
                });
                return;
            } else {
                shopCashDesk.CashModify(data).then(function (ret) {
                    $scope.getCashSetData();
                    configData.cashsetData.cashNum = data.cashNum;
                    configData.cashsetData.cashName = data.cashName;
                    configData.cashsetData.remark = data.remark;
                    $api.setStorage('configData', configData);
                    baison_app.api.toast({msg: $rootScope.language.TIPS_OPTION_SUCCESS});
                });
                $scope.cancle();
            }
        };

        //选择按钮
        $scope.choices = function (list) {
            var param = {
                'shop_code': $rootScope.current_shop.ShopCode,
                'cashNum': list.cashNum
            };
            shopCashDesk.getCashList(param).then(function (ret) {
                var list = ret.data.data.data[0];
                if (list.remark == null) {
                    list.remark = '';
                }
                configData.cashsetData.cashNum = list.cashNum;
                configData.cashsetData.cashName = list.cashName;
                configData.cashsetData.remark = list.remark;
                $api.setStorage('configData', configData);
                $scope.getCashSetData();
            });
        };
    }];
var SettingChecksetCtrl = ['$scope', '$rootScope', 'checkGetList', 'ngDialog',
    function ($scope, $rootScope, checkGetList, ngDialog) {
        $scope.submited_orde = '排序';
        $scope.configData = $api.getStorage('configData');
        $scope.rder = 'CheckOrder';
        //当前二级菜单为check_set  结算方式
        $scope.curr = 'check_set';
        $scope.checklist = [];
        //开启关闭更改支付方式顺序
        $scope.able_change = false;
        //获取全部的结算方式
        $scope.checklist = [];
		var can_used_feifan = false;
		var systype = baison_app.api.systemType;
		if(systype == 'android'){
			can_used_feifan = true;
		}
        var dataCurrency = [];
        $scope.get_list_check = function () {
            checkGetList.get_list().then(function (response) {
				//add by liuwei 20170831 去除VIP储值卡005
				if(!can_used_feifan){
					response.checkType.forEach(function(n){
						var arr_code = ["005","003","027","028","029","ALIPAYACCOUNT","COUPON","POINT","DISCOUNT","PCARD","MCARD","MCOUPON","MDISCOUNT","PCREDIT","028","029","103"];
						if($.inArray(n.CheckCode,arr_code)<0){
							$scope.checklist.push(n);
						}
					});
				}else{
					response.checkType.forEach(function(n){
						var arr_code = ["005","003","027","028","029","ALIPAYACCOUNT","COUPON","POINT","DISCOUNT","PCARD","MCARD","MCOUPON","MDISCOUNT","PCREDIT","028","029"];
						if($.inArray(n.CheckCode,arr_code)<0){
							$scope.checklist.push(n);
						}
					})
				}
                dataCurrency = response.currencyType;
//                $scope.configData = $api.getStorage('configData');
                var checklist = $scope.configData.checklist;
                var currencylist = $scope.configData.currencylist;
                var order_length = 0;
                for (var i in $scope.configData.old_order) {
                    order_length = 1;
                }
                if (order_length == 0) {
                    $scope.checklist.forEach(function (n) {
                        n.CheckOrder = n.CheckOrder * 1;
                        n.OldOrder = n.CheckOrder;
                        $scope.configData.old_order[n.CheckCode] = n.CheckOrder * 1;
                    });
                } else {
                    $scope.checklist.forEach(function (n) {
                        n.CheckOrder = $scope.configData.old_order[n.CheckCode] * 1;
                        n.OldOrder = n.CheckOrder;
                    });
                }
                $scope.checklist.forEach(function (n) {
                    if (-1 !== checklist.indexOf(n.CheckCode)) {
                        //已选中
                        n.selected = true;
                    } else {
                        //未选中
                        n.selected = false;
                    }
                });
                dataCurrency.forEach(function (n) {
                    if (-1 !== currencylist.indexOf(n.cur_code)) {
                        //已选中
                        n.selected = true;
                    } else {
                        //未选中
                        n.selected = false;
                    }
                });
                dataCurrency.filter(function (x) {
                    if (x.cur_code == $scope.configData.standard_coin) {
                        x.selected = true;
                    }
                });
                $scope.currencylist = dataCurrency;
            });
        };
        $scope.get_list_check();

        //汇率查看
        $scope.show_rate = function () {
            $scope.all_currency = dataCurrency;
            $scope.change_time = dataCurrency[0].lastchanged;
            $scope.currency_money1 = 1;
            currency = ngDialog.open({closeByDocument: false,
                template: './html/setting/dialog/show_currency_rate.html',
                disableAnimation: true,
                scope: $scope,
//                closeByDocument: false
                trapFocus: false,
                controller: ['$scope', function ($scope) {
                        $scope.change_rate1 = function () {
                            $scope.currency_money2 = 1 / $scope.rate2 * $scope.currency_money1 * $scope.rate1;
                            $scope.currency_money2 = ($scope.currency_money2.toFixed(2) != 'NaN') ? $scope.currency_money2.toFixed(2) : 0;
                        };
                        $scope.change_rate2 = function () {
                            $scope.currency_money2 = 1 / $scope.rate2 * $scope.currency_money1 * $scope.rate1;
                            $scope.currency_money2 = ($scope.currency_money2.toFixed(2) != 'NaN') ? $scope.currency_money2.toFixed(2) : 0;
                        };
                        $scope.change_money1 = function () {
                            $scope.currency_money2 = 1 / $scope.rate2 * $scope.currency_money1 * $scope.rate1;
                            $scope.currency_money2 = ($scope.currency_money2.toFixed(2) != 'NaN') ? $scope.currency_money2.toFixed(2) : 0;
                        };
                        $scope.change_money2 = function () {
                            $scope.currency_money1 = 1 / $scope.rate1 * $scope.currency_money2 * $scope.rate2;
                            $scope.currency_money1 = ($scope.currency_money1.toFixed(2) != 'NaN') ? $scope.currency_money1.toFixed(2) : 0;
                        };
                    }]
            });
        };

        //开启关闭改变支付方式顺序
        $scope.submit_orde = function () {
            $scope.able_change = !$scope.able_change;
            if ($scope.able_change) {
                $scope.submited_orde = '保存';
            } else {
                $scope.submited_orde = '排序';
            }
            $api.setStorage('configData', $scope.configData);
            $scope.get_list_check();
//            $scope.checklist.forEach(function(n){
//                delete n.$$hashKey;
//                delete n.selected;
////                n.delete(n.$$hashKey);
//            });
//            checkGetList.save_check_order($scope.checklist).then(function(){
//                
//            }).catch(function(err){
//                baison_app.api.alert({msg:err,title:1111});
//            })
//            $scope.checklist.forEach(function (n) {
//                checkGetList.save_check_order($scope.checklist).then(function () {
//
//                }).catch(function (err) {
//                    baison_app.api.alert({msg: err, title: 1111});
//                });
//            });
        };

        $scope.change_order = function (ret, code, order) {
            //改变顺序
            if ($scope.able_change) {
                $scope.checklist[ret].selected = !$scope.checklist[ret].selected;
                $scope.checklist = $scope.checklist.map(function (x) {
                    if (x.CheckOrder == order) {
                        if (x.CheckCode != code) {
                            x.CheckOrder = $scope.configData.old_order[code] * 1;
                            $scope.configData.old_order[code] = $scope.configData.old_order[x.CheckCode] * 1;
                            $scope.configData.old_order[x.CheckCode] = x.CheckOrder * 1;
                        }
                    }
                    return x;
                });
            }
//            $scope.get_list_check();
            $api.setStorage('configData', $scope.configData);
        };

        //保存修改外币的结算方式
        $scope.selectCurrency = function (ret) {
            if ($scope.currencylist[ret].cur_code == $scope.configData.standard_coin) {
                $scope.currencylist[ret].selected = !$scope.currencylist[ret].selected;
                return;
            }
            if ($rootScope.purview['\/setting\/check_set'].show == 0) {
                $scope.currencylist[ret].selected = !$scope.currencylist[ret].selected;
                return;
            }
            var currencylist = [];
            $scope.currencylist.forEach(function (n) {
                if (n.selected === true) {
                    currencylist.push(n.cur_code);
                }
            });
            $scope.configData.currencylist = currencylist;
            $api.setStorage('configData', $scope.configData);
        };
        //保存修改结算方式
        $scope.selectCheck = function (ret) {
            if ($rootScope.purview['\/setting\/check_set'].show == 0 || $scope.able_change) {
                $scope.get_list_check();
                return;
            }
            var checklist = [];
            $scope.checklist.forEach(function (n) {
                if (n.selected === true) {
                    checklist.push(n.CheckCode);
                }
            });
            if (checklist.length == 0) {
                baison_app.api.toast({msg: $rootScope.language.TIP_SETTING_CHECK_CHOSE});
                checklist = ["001"];
                $scope.checklist[0].selected = true;
            }
//            var configData = $api.getStorage('configData');
            $scope.configData.checklist = checklist;
            $api.setStorage('configData', $scope.configData);
        };
    }];
var SettingUsermanageCtrl = ['$rootScope', '$scope', 'PosUser', 'ngDialog', 'ShopSetCheck',
    function ($rootScope, $scope, PosUser, ngDialog, ShopSetCheck) {
        ShopSetCheck();
        //当前二级菜单为user_manage  用户管理
        $scope.curr = 'user_manage';
        $scope.userlist = [];
        $scope.data = $api.getStorage('current_shop');
        if (typeof $scope.data != "undefined") {
            var filter = {
                'ShopCode': $scope.data.ShopCode
            };
            //获取用户
            PosUser.get_list_by_cond(filter).then(function (ret) {
                $scope.userlist = ret;
            });
        }

        //获取用户角色
//        if ($rootScope.purview['\/setting\/user_add_type'].show == 1) {
//            PosUser.get_user_role().then(function (ret) {
//                if (ret.length != '0') {
//                    $scope.user_type = ret[0].role_code;
//                    $scope.user_all_type = ret;
//                }
//            });
//        }
        //弹出编辑窗口
        $scope.userEdit = {};
        $scope.clickToEdit = function (list) {
            $scope.userEdit = list;
            edit = ngDialog.open({closeByDocument: false,
                preCloseCallback: function () {
                    PosUser.get_list_by_cond(filter).then(function (ret) {
                        $scope.userlist = ret;
                    });
                    return true;
                },
                template: './html/setting/user_manage/user_edit.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope
            });
        };
        //保存编辑数据
        $scope.editSubmit = function (userEdit) {
            if (typeof userEdit.UserName == 'undefined' || userEdit.UserName == '') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_USER_NAME
                });
            } else {
                var data = {
                    UserName: userEdit.UserName,
                    UserTel: userEdit.UserTel,
                    UserStatus: userEdit.UserStatus
                };
                PosUser.save_user_by_code(userEdit.UserCode, data).then(function (success) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: $rootScope.language[success.data.code]
                    });
                }).catch(function (err) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: err
                    });
                });
                ngDialog.close(edit);
            }
        };
        //解除绑定
        $scope.unBindSubmit = function (userEdit) {
//***************************************解除绑定为停用******************************************************************//
            if (typeof userEdit.UserName == 'undefined' || userEdit.UserName == '') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_USER_NAME
                });
//            } else if (typeof userEdit.UserTel == 'undefined' || userEdit.UserTel == '') {
//                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_MEMBER_TEL_CHECK
//                });
            } else {
                var data = {
                    UserName: userEdit.UserName,
                    UserTel: userEdit.UserTel,
                    UserStatus: 1
                };
                PosUser.save_user_by_code(userEdit.UserCode, data,2).then(function (success) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: $rootScope.language[success.data.code]
                    });
                }).catch(function (err) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: err
                    });
                });
                ngDialog.close(edit);
            }
//*************************************************************************************************************************//
//**************************原来接触绑定逻辑*****************************************************************************//            
            /*           var data = {
             UserCode: userEdit.UserCode,
             ShopCode: ''
             };
             PosUser.unBind_user_by_code(data.UserCode, data).then(function (success) {
             //            PosUser.save_user_by_code_local(data.UserCode, data).then(function (success) {
             PosUser.get_list_by_cond(filter).then(function (ret) {
             $scope.userlist = ret;
             });
             }).catch(function (err) {
             baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
             msg: $rootScope.language.TIP_INDEX_NO_INVENTORY
             });
             });
             ngDialog.close(edit);
             */
//*************************************************************************************************************************//            
        };
        //添加用户弹窗
        $scope.clickToAdd = function () {
            add = ngDialog.open({closeByDocument: false,
                template: './html/setting/user_manage/user_add.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                controller: ['$scope',
                    function ($scope) {
                        $scope.userAdd = {};
                        $scope.userAdd.role_id = $scope.user_type;
                        $scope.userAdd.UserStatus = 1;
                    }]
            });
        };
        //保存添加用户数据
        $scope.addSubmit = function (userAdd) {
            if (typeof userAdd != "undefined") {
                if (typeof userAdd.UserName == "undefined" || typeof userAdd.UserPass == "undefined") {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_USER_INFO_CHECK
                    });
                } else if (typeof userAdd.UserCode == "undefined") {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_REPORT_RIGHT_USER_CODE
                    });
                } else if (userAdd.UserCode == 000) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_USER_CODE_CHECK
                    });
                } else if (typeof userAdd.UserTel == "undefined") {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_TEL_INPUT_ERROR
                    });
                } else {
                    var data = {
                        UserCode: userAdd.UserCode,
                        UserName: userAdd.UserName,
                        UserTel: userAdd.UserTel,
                        UserStatus: userAdd.UserStatus,
                        UserPass: userAdd.UserPass,
                        ShopCode: $scope.data.ShopCode,
                        role_id: userAdd.role_id,
                        ShopCodeEx: "",
                        UserManage: 1,
                        UserSex: 2,
                        maxDiscount: "0",
                        maxPrice: "0.00",
                        maxRebate: "1.00",
                        minPrice: "0.00",
                        minRebate: "1.00",
                        signatureCode: userAdd.UserPass
                    };
                    PosUser.add_user_by_code(data).then(function () {
                        PosUser.get_list_by_cond({"ShopCode": $scope.data.ShopCode}).then(function (ret) {
                            $scope.userlist = ret;
                            ngDialog.close(add);
                        });
                    }).catch(function (err) {
                        baison_app.api.toast({msg: $rootScope.language[err]});
                    });
                }
            }
        };
        //弹出绑定店铺窗口
        $scope.clickToBind = function () {

            $scope.userBind = {};
            bind = ngDialog.open({closeByDocument: false,
                template: './html/setting/user_manage/user_bind.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope
            });
        };
        //搜索
        $scope.search = function (m) {
            PosUser.get_user_by_code(m).then(function (ret) {
                $scope.userBind = {};
                if (ret === 0) {
                    PosUser.get_user_by_code_from_server(m).then(function(n){
                        
                        var users = n.data.data;
                        if(users.user_code == undefined){
                            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_SEARCH_GOODS
                            });
                        }else{
                            $scope.userBind.UserStatus = users.status;
                            $scope.userBind.UserTel = (users.tel == undefined) ? '' : users.tel;
                            $scope.userBind.UserName = users.user_name;
                            PosUser.add_user_to_local(users);
                        }
                    });
                    
                } else if ($scope.userBind.ShopCode == $scope.data.ShopCode) {
                    $scope.userBind = {};
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_TEAM_CODE_CHECK
                    });
                }else {
                    $scope.userBind = ret;
                }
            });
        };
        //绑定店铺
        $scope.bindSubmit = function (m) {
//            var data = {
            $scope.userBind.UserCode = m.UserCode;
            $scope.userBind.UserTel = m.UserTel;
            $scope.userBind.UserStatus = m.UserStatus;
            $scope.userBind.ShopCode = $scope.data.ShopCode;
            delete $scope.userBind.UserPass;
//            };
//            $scope.userBind = [];
//            PosUser.save_user_by_code_local($scope.userBind.UserCode, $scope.userBind).then(function (success) {
            PosUser.save_user_by_code($scope.userBind.UserCode, $scope.userBind,1).then(function (success) {
                PosUser.get_list_by_cond(filter).then(function (ret) {
                    $scope.userlist = ret;
                });
                $scope.userBind = [];
            }).catch(function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                    msg: err
                });
            });
            ngDialog.close(bind);
            //            }
        };
    }];
var SettingUsermanage2Ctrl = ['$scope', '$rootScope', 'ngDialog', 'PosUser', 'ShopSetCheck',
    function ($scope, $rootScope, ngDialog, PosUser, ShopSetCheck) {
        ShopSetCheck();
        //当前二级菜单为user2_manage  用户管理
        $scope.curr = 'user2_manage';
        $scope.data = $api.getStorage('current_shop');
        if (typeof $scope.data != "undefined") {
            var filter = {
                'ShopCodeEx': $scope.data.ShopCode
            };
            PosUser.get_list_by_cond(filter).then(function (ret) {
                $scope.userTeam = ret;
            });
        }

        //弹出新增窗口
        $scope.clickToTeam = function () {
            $scope.userSearchTeam = [];
            co_add = ngDialog.open({closeByDocument: false,
                template: './html/setting/user_manage/user_team_add.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope
            });
        };
        //搜索
        $scope.search = function (m) {
            PosUser.get_user_by_code(m).then(function (ret) {
                $scope.userSearchTeam = ret;
                if (ret === 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_SEARCH_GOODS
                    });
                } else if ($scope.userSearchTeam.Status == 0 || $scope.userSearchTeam.ShopCodeEx === $scope.data.ShopCode) {
                    $scope.userSearchTeam = {};
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_TEAM_CODE_CHECK
                    });
                }
            });
        };
        //保存协作导购新增数据
        $scope.teamSubmit = function (userSearchTeam) {
            var data = {
                UserCode: userSearchTeam.UserCode,
                UserTel: userSearchTeam.UserTel,
                UserStatus: 1,
                ShopCodeEx: $scope.data.ShopCode
            };
            $scope.userSearchTeam = {};
            PosUser.save_cooperate_user_by_code(data.UserCode, data).then(function (success) {
                PosUser.get_list_by_cond(filter).then(function (ret) {
                    $scope.userTeam = ret;
                });
            }).catch(function (err) {
                baison_app.api.alert({msg: err});
            });
            ngDialog.close(co_add);
        };
        //弹出编辑窗口
        $scope.userEdit = {};
        $scope.clickToEdit = function (list) {
            $scope.userEdit = list;
            co_edit = ngDialog.open({closeByDocument: false,
                preCloseCallback: function (value) {
                    PosUser.get_list_by_cond(filter).then(function (ret) {
                        $scope.userTeam = ret;
                    });
                    return true;
                },
                template: './html/setting/user_manage/user_team_edit.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope
            });
        };
        //保存编辑数据
        $scope.editSubmit = function (userEdit) {
            if (typeof userEdit.UserName == 'undefined') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_USER_NAME
                });
            } else if (typeof userEdit.UserTel == 'undefined' || userEdit.UserTel == '') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_TEL_INPUT_ERROR
                });
            } else {
                var data = {
                    UserName: userEdit.UserName,
                    UserTel: userEdit.UserTel,
                    UserStatus: userEdit.UserStatus
                };
                PosUser.save_user_by_code(userEdit.UserCode, data).then(function (success) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: $rootScope.language[success.data.code]
                    });
                }).catch(function (err) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                        msg: err
                    });
                });
                ngDialog.close(co_edit);
            }
        };
        //解除绑定
        $scope.unBindSubmit = function (userEdit) {
            var data = {
                UserCode: userEdit.UserCode,
                ShopCodeEx: ''
            };
            PosUser.unBind_user_by_code(data.UserCode, data).then(function (success) {
                PosUser.get_list_by_cond(filter).then(function (ret) {
                    $scope.userTeam = ret;
                });
            }).catch(function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                    msg: err
                });
            });
            ngDialog.close(co_edit);
        };
    }];
var SettingCommonsetCtrl = ['$scope', '$rootScope', 'LanguageSet', '$location', 'get_api', 'checkGetList',
    function ($scope, $rootScope, LanguageSet, $location, get_api, checkGetList) {
        checkGetList.get_list().then(function (response) {
            $scope.currencylist = response.currencyType;
        });
        //当前二级菜单为common_set  设置配置项
        $scope.curr = 'common_set';
		var systype = baison_app.api.systemType;
		if(systype != 'android'){
			$scope.sys_type = false;
			
		}else{
			$scope.sys_type = true;
		}
        //初始化数据
        var settingCommonInit = function () {
            $scope.common_cur = '1';
            $scope.cashier_cur = '0';
            $scope.member_cur = '0';
            $scope.wailian_cur='0';
        };
        settingCommonInit();
        //通用选项
        $scope.switch_01 = 'curr';
        $scope.tab_common_list = function () {
            $scope.common_cur = 1;
            $scope.cashier_cur = 0; 
            $scope.member_cur = 0;
            $scope.wailian_cur=0;
            $scope.switch_01 = 'curr';
            $scope.switch_02 = '';
            $scope.switch_03 = '';
            $scope.switch_04 = '';
        };
        //收银选项
        $scope.switch_02 = '';
        $scope.tab_cashier_list = function () {
            $scope.common_cur = 0;
            $scope.cashier_cur = 1;
            $scope.member_cur = 0;
            $scope.wailian_cur=0;
            $scope.switch_01 = '';
            $scope.switch_02 = 'curr';
            $scope.switch_03 = '';
            $scope.switch_04 = '';
        };
        //会员选项
        $scope.switch_03 = '';
        $scope.tab_member_list = function () {
            $scope.common_cur = 0;
            $scope.cashier_cur = 0;
            $scope.member_cur = 1;
            $scope.wailian_cur=0;
            $scope.switch_01 = '';
            $scope.switch_02 = '';
            $scope.switch_03 = 'curr';
            $scope.switch_04 = '';
        };
        //外链选项
        $scope.switch_04 = '';
        $scope.tab_wailian_list = function () {
            $scope.common_cur = 0;
            $scope.cashier_cur = 0;
            $scope.member_cur = 0;
            $scope.wailian_cur=1;
            $scope.switch_01 = '';
            $scope.switch_02 = '';
            $scope.switch_03 = '';
            $scope.switch_04 = 'curr';

        };
        //模式设置
        if (isPC) {
            $scope.runMode_options = [
                {
                    id: 0,
                    name: $rootScope.language.TIP_SETTING_APP_MODEL_SINGAL
                },
                {
                    id: 1,
                    name: $rootScope.language.TIP_SETTING_APP_MODEL_PRIMAY
                },
                {
                    id: 2,
                    name: $rootScope.language.TIP_SETTING_APP_MODEL_SON
                }
            ];
        } else {
            $scope.runMode_options = [
                {
                    id: 0,
                    name: $rootScope.language.TIP_SETTING_APP_MODEL_SINGAL
                },
                {
                    id: 2,
                    name: $rootScope.language.TIP_SETTING_APP_MODEL_SON
                }
            ];
        }
        $scope.configData = $api.getStorage('configData');
		$scope.shanghu = $scope.configData.shanghu;
        $scope.shanghu_password = $scope.configData.shanghu_password;
        if ($api.getStorage('language') != undefined && $api.getStorage('language') != '') {
            var id = $api.getStorage('language');
        } else {
            var id = 'zh_cn';
        }
        //$scope.language_select = $scope.language_options[id];

        if ($api.getStorage('runMode') != undefined && $api.getStorage('runMode') != '') {
            var modeId = $api.getStorage('runMode').id;
        } else {
            var modeId = 0;
        }
        $scope.runMode_select = $scope.runMode_options[modeId];
        $scope.change = function (params) {
            if (1 == $scope.runMode_select.id) {
                var ip = getLocalIp();
                if (ip[0]) {
                    $scope.ip = ip[0];
                }
                $scope.port = 10530;
            } else if (2 == $scope.runMode_select.id) {
                $scope.url = "http://" + $scope.ip + ":" + $scope.port + "/";
            }
        }

        if ($scope.configData.zftd == undefined) {
            $scope.configData.zftd = 0;
        }
        $scope.processForm = function () {
            if ($scope.configData.commonpay_num > 11) {
                $scope.configData.commonpay_num = 11;
            }
            get_api.get_api($scope.shanghu,$scope.shanghu_password).then(function (res) {
//              var configData = $api.getStorage('configData');
                if (res.data.status == '1') {
                    $scope.configData.api_url = res.data.data.url;
                    $scope.configData.shanghu = $scope.shanghu;
                    $scope.configData.shanghu_password = $scope.shanghu_password;
                    //baison_app.api.toast({msg: $rootScope.language.TIP_INDEX_SET_SUCCESS});
                } else {
                    var configData2 = $api.getStorage('configData');
                    $scope.shanghu = configData2.shanghu;
                    $scope.shanghu_password = configData2.shanghu_password;
                    baison_app.api.alert({msg: $rootScope.language.TIPS_ERROR_CODE_OR_PASSWORD});
                }

                var stander_coin_check = $scope.configData.currencylist.filter(function (x) {
                    if (x == $scope.configData.standard_coin) {
                        return 1;
                    }
                });
                
                if (stander_coin_check != 1) {
                    $scope.configData.currencylist.push($scope.configData.standard_coin);
                }
                
                //保存设置项
                $api.setStorage('configData', $scope.configData);
            });

            //更新默认货币
            if ($scope.configData.currency_foreign == 1) {
                $scope.currencylist.forEach(function (n) {
                    if (n.cur_code == $scope.configData.standard_coin) {
                        $rootScope.StandardRate = n.rate;
                    }
                });
            } else {
                $rootScope.StandardRate = 1;
            }



            $api.setStorage('language', $scope.configData.language);
            $api.setStorage('xuanzhuan', $scope.configData.xuanzhuan);
            $api.setStorage('membAge', $scope.configData.membAge);
            if ($scope.configData.xuanzhuan == 0) {
                baison_app.api.setScreenOrientation({
                    orientation: 'landscape_left'
                });
            }

            if ($scope.configData.xuanzhuan == 1) {
                baison_app.api.setScreenOrientation({
                    orientation: 'landscape_right'
                });
            }

            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_SAVE_SUCCESS});
            if (!($scope.configData.language == id && $scope.runMode_select.id == modeId)) {
                LanguageSet.language_set($scope.configData.language).then(function (ret) {
                    $rootScope.language = ret.data;
                });
                $location.path('/index')
            }

        };
        //重置按钮
        $scope.resetForm = function () {
            var configData = $api.getStorage('configData');
            $scope.configData.moling = configData.moling;
            $scope.configData.keyboard = configData.keyboard;
            $scope.configData.daogou = configData.daogou;
            $scope.configData.moling = configData.moling;
            $scope.configData.molingtype = configData.molingtype;
            $scope.configData.xuanzhuan = configData.xuanzhuan;
            $scope.configData.membAge = configData.membAge;
            $scope.configData.no_ticket_return = configData.no_ticket_return;
            $scope.configData.language = configData.language;
            $scope.configData.commonpay_num = configData.commonpay_num;
            $scope.configData.outlink = configData.outlink;
            $scope.configData.default_input = configData.default_input;
            $scope.configData.molingRule = configData.molingRule;
        };

    }];
var SettingPrintsetCtrl = ['$scope', '$rootScope', 'Print', 'timeStamp2String', function ($scope, $rootScope, Print, timeStamp2String) {
        //当前二级菜单为print_set   打印设置
        $scope.curr = 'print_set';
        //打印设置信息
        $scope.printData = {};
        var selectvalue = '';
        var stockvalue = '';
        //获取打印方式
        var get_print_type = function(usb,feifan,lanya){
            return usb == 1 ? 3:feifan == 1 ?2:lanya;
        };
        //打印设置页面初始值
        var printInit = function () {
            var configData = $api.getStorage('configData');
            $scope.printData.selectvalue = configData.printData['selectvalue'];
            $scope.printData.addr = configData.printData['addr'];
            $scope.printData.tel = configData.printData['tel'];
            $scope.printData.check = configData.printData['check'];
            $scope.printData.printType = get_print_type(configData.printData['usb'],configData.feifan.feifan,configData.lanya); 
            $scope.printData.usb = configData.printData['usb'];
            $scope.printData.feifan = configData.feifan.feifan;
            $scope.printData.lanya = configData.lanya;
            $scope.printData.bluetooth = configData.printData['bluetooth'];
            $scope.printData.web_site = configData.printData['web_site'];
			$scope.printData.num = configData.printData['num']?configData.printData['num']:1;
        };
        //打印设置页面初始值
        printInit();
        //选择模版
        $scope.printTemplate = {};
        //获取小票模版名称
        Print.xp_select_tplname().then(function (ret) {
            //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:ret.length,title:'retret'});
            if (ret.length == 0) {
                $scope.printData.selectvalue = '';
            } else {
                if ($scope.printData.selectvalue == '' || typeof $scope.printData.selectvalue == 'undefined') {
                    $scope.printData.selectvalue = ret[0].id;
                    selectvalue = ret[0].id;
                    var configData = $api.getStorage('configData');
                    configData.printData['selectvalue'] = $scope.printData.selectvalue;
                    $api.setStorage('configData', configData);
                }
                $scope.printTemplate.template_options = ret;
            }

        });
        //获取库存模版
        Print.stock_select_tplname().then(function (ret) {
            //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:ret.length,title:'retret'});
            if (ret.length == 0) {
                $scope.printData.stockvalue = '';
            } else {
                if ($scope.printData.stockvalue == '' || typeof $scope.printData.stockvalue == 'undefined') {
                    $scope.printData.stockvalue = ret[0].id;
                    stockvalue = ret[0].id;
                    var configData = $api.getStorage('configData');
                    configData.printData['stockvalue'] = $scope.printData.stockvalue;
                    $api.setStorage('configData', configData);
                }
                $scope.printTemplate.stock_options = ret;
            }

        });
        //保存模版
        $scope.processForm = function () {
            //获取configData
            var configData = $api.getStorage('configData');
            //设置打印设置界面的信息
            if ($scope.printData.selectvalue == '') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_PRINT_RECEIPT
                });
                return;
            }
            if ($scope.printData.printType != 3 && $scope.printData.printType != 2) {
                if ($scope.printData.bluetooth == '') {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_PRINT_BLUE
                    });
                    return;
                }
            }

            configData.printData['selectvalue'] = $scope.printData.selectvalue;
            configData.printData['stockvalue'] = $scope.printData.stockvalue;
            configData.printData['addr'] = $scope.printData.addr;
            configData.printData['tel'] = $scope.printData.tel;
            configData.printData['check'] = $scope.printData.check;
            configData.printData['usb'] = $scope.printData.printType==3?1:0;
            configData.feifan.feifan = $scope.printData.printType==2?1:0;
            configData.lanya = $scope.printData.printType==1?1:0;
            configData.printData['bluetooth'] = $scope.printData.bluetooth;
            configData.printData['web_site'] = $scope.printData.web_site;
			configData.printData['num']=$scope.printData.num;
            //保存打印设置
            $api.setStorage('configData', configData);
            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_INDEX_SET_SUCCESS
            });
        };
        //重置
        $scope.reset = function () {
            //获取configData
            var configData = $api.getStorage('configData');
            $scope.printData.selectvalue = configData.printData['selectvalue'] == '' ? selectvalue : configData.printData['selectvalue'];
            $scope.printData.stockvalue = configData.printData['stockvalue'] == '' ? stockvalue : configData.printData['stockvalue'];
            $scope.printData.check = configData.printData['check'];
            $scope.printData.addr = configData.printData['addr'];
            $scope.printData.tel = configData.printData['tel'];
            $scope.printData.web_site = configData.printData['web_site'];
            $scope.printData.usb = configData.printData['usb'];
            $scope.printData.lanya = configData.lanya;
            $scope.printData.printType = get_print_type(configData.printData['usb'],configData.feifan.feifan,configData.lanya); 
            $scope.printData.feifan = configData.feifan.feifan;
            $scope.printData.bluetooth = configData.printData['bluetooth'];
			$scope.printData.num = configData.printData['num']?configData.printData['num']:1;
        };
        //获取测试打印小票信息
        var xp_gettestinfo = function () {
            var record = {};
            var configData = $api.getStorage('configData');
            var printData = configData.printData;
            var shop_tel = '';
            var shop_addr = '';
            var web_site = '';
            if (printData != undefined) {
                shop_addr = printData['addr'];
                shop_tel = printData['tel'];
                web_site = printData['web_site'];
            }
            record.record_code = '154654654';
            record.record_time = timeStamp2String(0, 'datetime');
            record.vip_code = '7987987';
            record.pay_money = '1000.00';
            record.total_num = '1';
            record.total_money = '1000.00';
            record.record_detail = [{
                    'num': '1',
                    'GoodsName': '羽绒服',
                    'SkuPropertyName': '红色xl',
                    'price': '1000.00',
                    'money': '1000.00'
                }];
            record.payment = [{
                    'code': '001',
                    'pay_money': '1000.00'
                }];
            record.promotion = [{
                'short_name': '测试促销',
                'dis_pro_money': '100'
            }];
            record.shop_name = $rootScope.current_shop.ShopName;
            record.user_code = $rootScope.user.UserCode;
            record.user_name = $rootScope.user.UserName;
            record.brand_name = $rootScope.language.TIP_ORDER_RECEIPT_BRAND_NAME;
            record.shop_addr = shop_addr;
            record.shop_tel = shop_tel;
            record.web_site = web_site;
            return record;
        };
        //打印测试小票
        $scope.test = function () {
            var record = xp_gettestinfo();
            //Print.xp_print($rootScope.language.TIPS_SET_PRINT_TEST_PRIECT, record);
            //是否自动打印小票
            var configData = $api.getStorage('configData');
            var printNum = parseInt(configData.printData['num'], 10);
            if (configData.printData) {
                        
                if(isNaN(printNum) || printNum < 1)
                {
                    printNum = 1;
                }
                var execute_print = function(print_index){
                    if(print_index >= printNum){
                        return;
                    }
                    Print.xp_print($rootScope.language.TIPS_SET_PRINT_TEST_PRIECT, record).then(function(){
                        print_index++;
                        execute_print(print_index);
                    });
                };
                execute_print(0);
            }
        };
		
       
        //蓝牙打印机配对
        $scope.btn_bluetooth = function () {
            $scope.printData.bluetooth = Print.bluetooth();
        };
    }];
/**
 * 数据下载页面控制器
 * @author jhua.zuo<jhua.zuo@baisonmail.com>
 * @date 2015-10-26
 */
var SettingPatchCtrl = ['$rootScope', '$scope', 'PatchList', 'PatchDownload', 'ngDialog', 'ShopSetCheck',
    function ($rootScope, $scope, PatchList, PatchDownload, ngDialog, ShopSetCheck) {
        //当前二级菜单为patch下载数据
        ShopSetCheck();
        $scope.curr = 'patch';
        $scope.list = {};
        //获取补丁列表
        $rootScope.patch_uninstall = false;
        var init_patch = function () {
            PatchList().then(function (response) {
                //console.log(JSON.stringify(response));
                $scope.list = response.data.data;
            });
        };
        //点击下载动作
        $scope.download = function (patch) {
//            baison_app.api.alert({msg: patch, title: 'patch'});
            if (patch['patch_status'] == 'TIP_INDEX_NOT_DOWNLOAD') {//服务器就是中文，不能改成英文。。。
                $scope.patchflag = true;
                baison_app.api.showProgress({
                    text: '',
                    title: $rootScope.language.TIP_INDEX_DOWNLOAD,
                    modal: false
                });
                PatchDownload.patch_download(patch).then(function () {
                    //baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.patch_status});
                    //baison_app.api.hideProgress();
                    PatchList().then(function (response) {
                        $scope.list = response.data.data;
                        $scope.patchflag = false;
                        baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.patch_status});
                        baison_app.api.hideProgress();
                    });
                });
            } else if (patch['patch_status'] != 'TIP_INDEX_FIXED') {//服务器就是中文，不能改成英文。。。
                $scope.patchflag = true;
                baison_app.api.showProgress({
                    text: '',
                    title: $rootScope.language.TIP_INDEX_FIXING,
                    modal: false
                });
                PatchDownload.patch_install(patch);
                $scope.cur_install = patch.patch_code;
            }
        };
        //点击重新下载
        $scope.redownload = function (patch) {  //不用管状态重新下载与安装
            $scope.patchflag = true;
            baison_app.api.showProgress({
                text: '',
                title: $rootScope.language.TIP_INDEX_DOWNLOAD,
                modal: false
            });
            PatchDownload.patch_download(patch).then(function () {
                PatchList().then(function (response) {
                    $scope.list = response.data.data;
                    $scope.patchflag = false;
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.patch_status});
                    baison_app.api.hideProgress();
                });
            });
        };



        $rootScope.$on('install_finish', function (event, data) {
            //baison_app.api.alert({msg:$scope.patchflag,title:'event'});
            if ($scope.cur_install != data && !$scope.patchflag) {
                return;
            }
            PatchList().then(function (response) {
                $scope.list = response.data.data;
                $scope.patchflag = false;
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.patch_status});
                $rootScope.purviewGetById();
                baison_app.api.hideProgress();
            });
        });
        //查看下载日志
        $scope.btn_log = function (remarklog) {

            var logdata = [];
            windowid = ngDialog.open({closeByDocument: false,
                template: './html/setting/dialog/patch_loglist.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                controller: ['$scope', function ($scope) {
                        if (remarklog != null && remarklog != '') {
                            var logarr = remarklog.split(';');
                            if (logarr != null && logarr != '') {
                                $.each(logarr, function (i, v) {
                                    var tdarr = v.split(',');
                                    var tdobj = {};
                                    tdobj.shop_code = $rootScope.current_shop.ShopName;
                                    tdobj.lastchanged = tdarr[1];
                                    tdobj.patch_code = tdarr[2];
                                    tdobj.patch_status = tdarr[3];
                                    logdata.push(tdobj);
                                });
                                $scope.log_list = logdata;
                            } else {
                                var tdarr = v.split(',');
                                var tdobj = {};
                                tdobj.shop_code = $rootScope.current_shop.ShopName;
                                tdobj.lastchanged = tdarr[1];
                                tdobj.patch_code = tdarr[2];
                                tdobj.patch_status = tdarr[3];
                                logdata.push(tdobj);
                                $scope.log_list = logdata;
                            }

                        } else {
                            $scope.log_list = [];
                        }

                    }]
            });
        };
        //关闭对话框按钮
        $scope.log_window_close = function () {
            ngDialog.close(windowid);
        };
        //刷新按钮
        $scope.btn_refresh = function () {
            PatchList().then(function (response) {
                $scope.list = response.data.data;
            });
        };
        init_patch();
    }];
var SettingWaituploadCtrl = ['$q', '$scope', '$rootScope', 'waitUpLoad', '$location', 'panDian', 'dbDelete', 'ThirdDev','BaseGoods',
    function ($q,$scope, $rootScope, waitUpLoad, $location, panDian, dbDelete, ThirdDev,BaseGoods) {
        //当前二级菜单为wait_upload  未上传数据
        var configData = $api.getStorage('configData');
        $scope.configData = configData;
        $scope.curr = 'wait_upload';
        $scope.is_lqx = ThirdDev.is_lqx();
        var busy = 0;
        var prompt = '';
        //设定上传频率
        $scope.change_auto_load = function () {
            configData.offline_receipt = $scope.configData.offline_receipt;
            configData.offline_vip = $scope.configData.offline_vip;
            configData.auto_load = $scope.configData.auto_load;
            $api.setStorage('configData',configData);
            //$rootScope.setConfigData();
        };
        //获取未上传数据
        var get_wait_upload_data = function () {
            waitUpLoad.receipt_record_get_wait_upload_group_list().then(function (data) {
                if (data != undefined && data != null) {
                    $scope.receipt_list = data;
                    $scope.receipt_count = data.length;
                } else {
                    $scope.receipt_count = 0;
                }
                waitUpLoad.vip_get_wait_upload_group_list().then(function (data) {
                    if (data != undefined && data != null) {
                        $scope.vip_list = data;
                        $scope.vip_count = data.length;
                    } else {
                        $scope.vip_count = 0;
                    }
                    waitUpLoad.take_stock_get_wait_upload_group_list().then(function (data) {
                        if (data != undefined && data != null) {
                            $scope.take_stock_record_list = data;
                            $scope.stock_count = data.length;
                        } else {
                            $scope.stock_count = 0;
                        }

                        if (prompt != '') {
                            baison_app.api.hideProgress();
                            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: prompt});
                            prompt = '';
                        } else {
                            baison_app.api.hideProgress();
                        }

                    });
                });
            });
        };
        var waitUpLoadInit = function () {
            $scope.str_upload = true;
            $scope.record_cur = '1';
            $scope.vip_cur = '0';
            $scope.stock_cur = '0';
            $scope.receipt_list = [];
            $scope.vip_list = [];
            $scope.take_stock_record_list = [];
            $scope.buttonRefresh = '1';
            get_wait_upload_data();
        };
        waitUpLoadInit();
        //tab 离线小票\
        $scope.switch_01 = 'curr'
        $scope.tab_receipt_list = function () {
            $scope.str_upload = true;
            $scope.record_cur = '1';
            $scope.vip_cur = '0';
            $scope.stock_cur = '0';
            $scope.switch_01 = 'curr';
            $scope.switch_02 = '';
            $scope.switch_03 = '';
            $scope.buttonRefresh = '1';
        };
        //tab 未上传会员
        $scope.switch_02 = '';
        $scope.tab_vip_list = function () {
            $scope.str_upload = true;
            $scope.record_cur = '0';
            $scope.vip_cur = '1';
            $scope.stock_cur = '0';
            $scope.switch_01 = '';
            $scope.switch_02 = 'curr';
            $scope.switch_03 = '';
            $scope.buttonRefresh = '1';
        };
        //tab 离线盘点数据
        $scope.switch_03 = '';
        $scope.tab_take_stock_record_list = function () {
            $scope.str_upload = false;
            $scope.record_cur = '0';
            $scope.vip_cur = '0';
            $scope.stock_cur = '1';
            $scope.switch_01 = '';
            $scope.switch_02 = '';
            $scope.switch_03 = 'curr';
            $scope.buttonRefresh = '1';
        };
        //获取服务器上的账面数
        var get_stock_num = function(data){
            var deferredInstall = {};
            var promiseInstall = {};
            data.forEach(function(n,i){
                deferredInstall[i] = $q.defer();
                promiseInstall[i] = deferredInstall[i].promise;
                BaseGoods.get_stock_num_by_goodCode(n.goods_code).then(function(res){
                    console.log(res);
                    n.SkuNum = res.data.data.data[0].stock_num;
                    deferredInstall[i].resolve(i + '执行成功!');
                });
            });
            return $q.all(promiseInstall);
        };
        //离线盘点详情
        $scope.take_stock_record_detail = function (record_code) {
            $scope.buttonRefresh = '0';
            $scope.pdty = false;
            //根据单号查找到相应的盘点单据详细信息
            panDian.take_stock_get_wait_upload_detail(record_code).then(function (ret) {
                //console.log(ret);
                if(ret[0].take_stock_type == '001'){
                    $scope.pdty = true;
                }
                get_stock_num(ret).then(function(){
                    $scope.take_stock_record_detail_list = ret;
                });
                // ret.forEach(function(n){
                //     BaseGoods.get_stock_num_by_goodCode(n.goods_code).then(function(res){
                //         console.log(res);
                //         n.SkuNum = res.data.data.data[0].stock_num;
                //     });
                // });
                
            });
        };
        //上传离线盘点单据信息
        $scope.stock_upload = function (stock_detail) {
            //console.log(stock_detail);
            //根据单号获取盘点主信息
            panDian.take_stock_record_by_record_code(stock_detail[0].record_code).then(function (response) {
                if (Object.keys(response).length > 0) {
                    var record = response[0];
                    var record_detail = stock_detail;
                    if (Object.keys(record).length > 0 && Object.keys(record_detail).length > 0) {
                        //林清轩使用
                        if (ThirdDev.is_lqx()) { //$rootScope.purview['\/cunhuo\/pandianTask_list'].show == 0
                        	
                            panDian.take_stock_record_add_detail_api(record, record_detail).then(function (ret) {
                                if (ret.data.status == 1) {
                                    //更新本地盘点主单据为已上传
                                    panDian.update_stock_record(record.record_code);
                                    get_wait_upload_data();
                                    $scope.tab_take_stock_record_list();
                                    baison_app.api.toast({msg: ret.data.message});
                                	//预盈亏
					                panDian.profit_and_loss_by_app(record, record_detail).then(function (ret) {
					                    if (ret.data.status == 1) {
//					                        baison_app.api.toast({
//					                            msg: $rootScope.language[ret.data.code]
//					                        });
					                        $location.path('/cunhuo/pandian_list');
					                    }
					                });
                                } else {
                                    baison_app.api.toast({
                                        msg: ret.data.message
                                    });
                                }
                            });
                        } else {
                            //lite使用
                            panDian.add_take_stock_recordDetail_api(record.record_code, record_detail).then(function (ret) {
                                if (ret.data.status == 1) {
                                    //更新本地盘点主单据为已上传
                                    panDian.update_stock_record(record.record_code);
                                    get_wait_upload_data();
                                    $scope.tab_take_stock_record_list();
                                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: ret.data.message});
                                } else {
                                    baison_app.api.toast({
                                        msg: ret.data.message
                                    });
                                }
                            });
                        }
                    }
                } else {
                    return;
                }
            });
        };
        //右滑操作
        $scope.close_detail = function () {
            $scope.str_upload = false;
            $scope.record_cur = '0';
            $scope.vip_cur = '0';
            $scope.stock_cur = '1';
            $scope.switch_01 = '';
            $scope.switch_02 = '';
            $scope.switch_03 = 'curr';
            $scope.buttonRefresh = '1';
        };
        //检查是否有数据上传
        var check_right_upload_data = function (list) {
            if (list.length == 0) {
                return 0;
            }
            for (var i = 0; i < list.length; i++) {
                var re = /fail/;
                if (!re.test(list[i].comment)) {
                    return 1;
                }
            }
            return 0;
        };
        //btn 上传离线数据
        $scope.btn_upload = function () {

            var data = {};
            if ($scope.record_cur == '1') {
                data = $scope.receipt_list;
                if (check_right_upload_data(data) == 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_UPLOAD_DATA});
                    return;
                }
                baison_app.api.showProgress({
                    text: '',
                    title: $rootScope.language.TIP_SETTING_UPLOAD,
                    modal: false
                });
                if(busy == 1){
                    return;
                }
                busy = 1; //结算中
                waitUpLoad.receipt_record_loacl_to_api(data).then(function (ret) {
                    busy = 0;
                    prompt = $rootScope.language.TIPS_CUNHUO_CONFIRM_SUCCESS;
                    get_wait_upload_data();
                });
            } else if ($scope.vip_cur == '1') {
                data = $scope.vip_list;
                if (check_right_upload_data(data) == 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_UPLOAD_DATA});
                    return;
                }
                baison_app.api.showProgress({
                    text: '',
                    title: $rootScope.language.TIP_SETTING_UPLOAD,
                    modal: false
                });
                waitUpLoad.vip_loacl_to_api(data).then(function (ret) {
//                  prompt = '上传完成';
                    get_wait_upload_data();
                });
            }

        };
        //btn 清除离线废数据
        $scope.btn_cleardata = function () {
            if ($scope.record_cur == '1') { //小票废数据
                $.each($scope.receipt_list, function (i, v) {
                    var re = /fail/;
                    if (re.test(v.comment)) {
                        dbDelete('PosReceiptRecord', {'record_code': v.record_code}).then(function (ret) {
                            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_CLEAR});
                            get_wait_upload_data();
                        });
                    }

                });
            } else if ($scope.vip_cur == '1') { //会员废数据
                $.each($scope.vip_list, function (i, v) {
                    var re = /fail/;
                    if (re.test(v.comment)) {
                        dbDelete('crm_customer', {'customer_code': v.customer_code}).then(function (ret) {
                            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_CLEAR});
                            get_wait_upload_data();
                        });
                    }

                });
            }

        };
        //btn 刷新
        $scope.refresh_data = function () {
            get_wait_upload_data();
        };
    }];
//陈列数
var SettingChenLieCtrl = ['$scope', '$rootScope', 'ngDialog', 'BaseGoods',
    function ($scope, $rootScope, ngDialog, BaseGoods) {
        $scope.curr = 'chen_lie';
        var window_id = 0;
        /////////////////////////////////////////////
        var choseArr = {};
        //定义数组用于存放前端显示
        $scope.check = {};
        //默认未选中
        var length = 10;
        //查询条件
        $scope.input_keyword = ''; //界面输入框的内容
        /////////////////////////////////////////
        //全选
        //选中一条
        $scope.chooseOne = function (index, sku, check) {//单选或者多选
            if (check == true) {//选中
                choseArr[index] = sku;
            } else {
                delete choseArr[index];
                //取消选中
                delete $scope.check[index];
            }
        };
        //全部选择
        $scope.cAll = function (master, skus) {
            //$scope.master = true;
            $.each(skus, function (i, n) {
                choseArr[n.SkuCode] = n;
                $scope.check[n.SkuCode] = true;
            });
        };
        //取消全选
        $scope.cancelAll = function () {
            //$scope.master = false;
            $.each(choseArr, function (i, n) {
                $scope.check[i] = false;
            });
            choseArr = {};
            $scope.check = {};
        };
        //高级查询
        $scope.search = function () {
            $scope.input_keywords = '';
            window_id = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/setting/chen_lie/search.html',
                disableAnimation: true,
                scope: $scope,
            });
        };
        //批量编辑陈列数
        $scope.editAll = function () {
            if (Object.keys(choseArr).length <= 0) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_SELECT_GOODS
                });
                return;
            }
            $scope.num = '';
            window_id = ngDialog.open({closeByDocument: false,
                template: './html/setting/chen_lie/edit_all.html',
                disableAnimation: true,
                scope: $scope,
//                closeByDocument: false
                trapFocus: false
            });
        };
        //单条编辑陈列数
        $scope.edit = function (sku) {
            $scope.sku = sku;
            $scope.sku.num = sku.SkuChenlie;
            window_id = ngDialog.open({closeByDocument: false,
                template: './html/setting/chen_lie/edit.html',
                disableAnimation: true,
                scope: $scope,
//                closeByDocument: false
                trapFocus: false
            });
        };
        //获取所有sku
        var get_all_skus = function () {
            $scope.skus = [];
            BaseGoods.getChenlieAndName_By_all_skus(0, length).then(function (ret) {
                $.each(ret, function (i, n) {
                    $scope.skus.push(n);
                });
                $scope.is_show = true;
            });
        };
        get_all_skus();
        //弹框处理===================================
        //查询根据商品编号查询
        $scope.select_goods = function (keyword) {
            if (keyword == '') {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CASHIER_INPUT_GOODS_CODE});
                return;
            }
            BaseGoods.get_sku_by_code(keyword).then(function (response) {
                if (Object.keys(response).length <= 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_CANT_FOUND_RESULT});
                    get_all_skus();
                    return;
                }
                $scope.skus = response;
                $scope.is_show = "";
            }, function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: err});
            });
            ngDialog.close(window_id);
        };
        $scope.save_edit = function (sku) {
            var re = /^\+?(0|[1-9][0-9]*)$/;
            if (sku.num == undefined) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_EMPTY
                });
                return;
            } else if (sku.num < 0) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_EARLY1
                });
                return;
            } else if (!re.test(sku.num)) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_TYPE
                });
                return;
            }

            //更新陈列数到表,从表里面获取
            BaseGoods.set_SkuChenlie(sku);
            get_all_skus();
            ngDialog.close(window_id);
        };
        //批量修改保存陈列数
        $scope.save_editAll = function (num) {
            var re = /^\+?(0|[1-9][0-9]*)$/;
            if (num == undefined) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_EMPTY
                });
                return;
            } else if (num < 0) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_EARLY1
                });
                return;
            } else if (!re.test(num)) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_NUM_TYPE
                });
                return;
            }
            //更新陈列数到表,从表里面获取
            BaseGoods.set_SkuChenlieAll(num, choseArr).then(function (ret) {
                length = 10;
                get_all_skus();
            });
            //批量修改完成取消全选按钮
            $.each(choseArr, function (i, n) {
                $scope.check[i] = false;
            });
            $scope.master = false;
            $scope.check = {};
            choseArr = {};
            ngDialog.close(window_id);
        };
        //取消
        $scope.clear = function () {
            ngDialog.close(window_id);
        };
        //滑动事件加载锁========================================
        //往下点击获取更多
        $scope.scoll = {};
        //滚动加载器
        $scope.scoll.busy = false;
        $scope.scoll.nextpage = function () {
            if ($scope.scoll.busy) {
                return;
            }
            baison_app.api.toast({
                msg: $rootScope.language.COMMON_LOADING
            });
            $scope.scoll.busy = true;
            BaseGoods.getChenlieAndName_By_all_skus(length, 10).then(function (ret) {
                length = length + ret.length;
                if (ret.length > 0) {
                    $.each(ret, function (i, n) {
                        $scope.skus.push(n);
                    });
                    $scope.scoll.busy = false;
                } else {
                    baison_app.api.toast({
                        msg: $rootScope.language.TIPS_CUNHUO_MESSAGE
                    });
                    $scope.is_show = "";
                }
            });
        };
    }];
//库存参数设置
var SettingStockSynchCtrl = ['$scope', '$rootScope', '$location', '$interval', 'BaseGoods', 'ReceiptRecord', 'timeStamp2String', 'ThirdDev', 'printWaitMsg','closePrintWaitMsg',
    function ($scope, $rootScope, $location, $interval, BaseGoods, ReceiptRecord, timeStamp2String, ThirdDev,
	printWaitMsg,closePrintWaitMsg) {
        $scope.curr = 'stock_synch';
        $scope.is_lqx = ThirdDev.is_lqx();
        $scope.synchroing = false; //同步中判断 false 为没有同步 true为正在同步
        var time;
        //库存更新结果
        var result = {};
        $scope.configData = $api.getStorage('configData');
        //保存设置
        $scope.save = function () {
            $api.setStorage('configData', $scope.configData);
            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_SAVE_SUCCESS
            });
        };
        //立即同步执行
        $scope.synchro = function () {
            var length = 200;
            stock_syn(length);
        };
        //是否显示同步失败
        $scope.showFail = function (check) {
            if (check == true) {
                //删选失败的数据
                $scope.results = [];
                var data = $api.getStorage('stock') ? $api.getStorage('stock') : [];
                $.each(data, function (i, n) {
                    if (n.result == 1) {
                        $scope.results.push(n);
                    }
                });
            } else {
                initKucun_syn();
            }
        };
        //同步结果中立即同步
        $scope.synstock = function (syn) {
            if (syn == 1) {
                var length = 200;
                stock_syn(length);
            }
        };
        //库存同步
        var stock_syn = function (length) {
            var configData = $api.getStorage('configData');
            if (configData.is_syn == 1) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_UPLOAD_SWITCH
                });
                return;
            }
            
            if($scope.synchroing){
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SYNCHROING
                });
                return;
            }
            $scope.synchroing = true;
			//add by liuwei 2017 05 31 同步等待信息
			var msg = "库存同步中...";
            var wait_data = printWaitMsg(msg);
            //库存更新到本地（手动更新）
            //判断本地是否有已支付未上传的小票
            ReceiptRecord.get_list_local_not_upload().then(function (ret) {
                //本地没有未上传的小票单据
                if (Object.keys(ret).length == '') {
                    //通过权限判断：林清轩还是lite使用
					function CycleSyn(n){
						BaseGoods.get_skunum_from_goods_inv(n,length).then(function (ret) {
							if(ret.data.status == 1){
								if (ret.data.data && ret.data.data.length > 0) {
									BaseGoods.syn_local_sku_num(ret.data.data);
									if(ret.data.data.length == length){
										//length = n + length;
										return CycleSyn( n +length);
									}else{
										//add by liuwei 2017 05 31 同步等待信息
										closePrintWaitMsg("fail",wait_data);
										//库存更新成功
										baison_app.api.toast({
											msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY
										});
										result = {
											'syn': 0, //表示成功
											'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
											'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
											'time': timeStamp2String(new Date(), 'datetime'),
											'result': 0,
											'reason': $rootScope.language.TIPS_CASHIER_NOT_AVAILABLE
										};
										setKuCun_syn(result);
										$scope.synchroing = false;
										return;
									}
								}else if(ret.data.data && ret.data.data.length <= 0){
									//add by liuwei 2017 05 31 同步等待信息
									closePrintWaitMsg("fail",wait_data);
									//库存更新成功
									baison_app.api.toast({
										msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY
									});
									result = {
										'syn': 0, //表示成功
										'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
										'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
										'time': timeStamp2String(new Date(), 'datetime'),
										'result': 0,
										'reason': $rootScope.language.TIPS_CASHIER_NOT_AVAILABLE
									};
									setKuCun_syn(result);
									$scope.synchroing = false;
									return;
								}
							}else{
								//add by liuwei 2017 05 31 同步等待信息
								closePrintWaitMsg("fail",wait_data);
								baison_app.api.toast({
									msg: $rootScope.language.TIP_INDEX_NO_INVENTORY
								});
								result = {
									'syn': 1, //表示同步失败
									'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
									'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
									'time': timeStamp2String(new Date(), 'datetime'),
									'result': 1, //1表示失败
									'reason': $rootScope.language.TIP_INDEX_NO_INVENTORY
								};
								$scope.synchroing = false;
								setKuCun_syn(result);
							}
						}).catch(function (err) {
							//add by liuwei 2017 05 31 同步等待信息
							closePrintWaitMsg("fail",wait_data);
                            baison_app.api.toast({
                                //msg: err
                                msg : $rootScope.language.TIP_INDEX_THRER_INVENTORY_FAIL
                            });
                            result = {
                                'syn': 1, //表示同步失败
                                'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                'time': timeStamp2String(new Date(), 'datetime'),
                                'result': 1, //1表示失败
                                'reason': $rootScope.language.TIP_INDEX_SEARCH_TYPE
                            };
                            $scope.synchroing = false;
                            setKuCun_syn(result);
                        });
					}
					CycleSyn(0);
				} else {
					//add by liuwei 2017 05 31 同步等待信息
					closePrintWaitMsg("fail",wait_data);
                    baison_app.api.toast({
                        msg: $rootScope.language.TIP_INDEX_NO_INVENTORY
                    });
                    result = {
                        'syn': 1,
                        'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                        'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                        'time': timeStamp2String(new Date(), 'datetime'),
                        'result': 1,
                        'reason': $rootScope.language.TIP_INDEX_NOT_UPLOAD_RECEIPT
                    };
                    $scope.synchroing = false;
                    setKuCun_syn(result);
                }
            });
        };
        //同步结果保存
        var setKuCun_syn = function (result) {
            $scope.results.push(result);
            $api.setStorage('stock', $scope.results);
        };
        //初始化
        var initKucun_syn = function () {
            $scope.results = $api.getStorage('stock') ? $api.getStorage('stock') : [];
        };
        initKucun_syn();
    }];
var SettingSkuPriceSynchCtrl = ['$scope', '$rootScope', '$location', '$interval', '$q', 'BaseGoods', 'ReceiptRecord',
    function ($scope, $rootScope, $location, $interval, $q, BaseGoods, ReceiptRecord) {
        $scope.curr = 'sku_price_synch';
        $scope.configData = {};
        $scope.configData.skuPriceSynch = {};
        var time;
        var base_num = 100;
        var update_sku_deferred = {};
        var update_sku_promise = {};
        var update_status = 0;
        //库存更新结果
        var result = {};
        $scope.configData = $api.getStorage('configData');
        //保存设置
        $scope.save = function () {
            $api.setStorage('configData', $scope.configData);
            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_INDEX_SET_SUCCESS
            });
        };
        //立即同步执行
        $scope.synchro = function () {
            sku_price_syn();
        };
        //是否显示同步失败
        $scope.showFail = function (check) {
            if (check == true) {
                //删选失败的数据
                $scope.results = [];
                var data = $api.getStorage('skuPrice') ? $api.getStorage('skuPrice') : [];
                $.each(data, function (i, n) {
                    if (n.result == 1) {
                        $scope.results.push(n);
                    }
                });
            } else {
                initSkuPrice_syn();
            }
        };
        //同步结果（立即同步）
        $scope.synSkuPrice = function (syn) {
            if (syn == 1) {
                sku_price_syn();
            }
        };
        //生成条件
        var update_batch_skus_price = function (offset, all_len, index) {
            BaseGoods.get_batch_skus(offset, base_num).then(function (ret) {
                var skus = ret;
                var where = '';
                var len = skus.length;
                $.each(skus, function (k, v) {
                    if (k == len - 1) {
                        where += ' (goods_code' + ' = ' + v.SkuCode + ')';
                    } else {
                        where += ' (goods_code' + ' = ' + v.SkuCode + ') or';
                    }
                });
                var param = {};
                param.where = where;
                BaseGoods.get_batch_skus_price(param).then(function (ret) {

                    var skus = ret.data.data;
                    BaseGoods.update_batch_skus_price(skus).then(function () {

                        if ((offset + base_num) >= all_len) {

                            baison_app.api.hideProgress();
                            baison_app.api.toast({msg: $rootScope.language.TIP_SETTING_PRICE});
                            update_status = 0;
                            var result = {
                                'syn': 0, //表示同步成功
                                'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                'time': new Date().toLocaleTimeString(),
                                'result': 0, //1表示失败
                                'reason': $rootScope.language.TIPS_CASHIER_NOT_AVAILABLE
                            };
                            setSkuPrice_syn(result);
                        } else {
                            offset = offset + base_num;
                            update_batch_skus_price(offset, all_len, index + 1);
                        }


                    });
                });
            });
        };
        //价格同步
        var sku_price_syn = function () {
            var configData = $api.getStorage('configData');
            if (configData.skuPriceSynch.is_syn == 1) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_SETTING_UPLOAD_SWITCH
                });
                return;
            }
            if (update_status == 1) {
                baison_app.api.toast({msg: $rootScope.language.TIP_SETTING_UPLOAD_BUSY});
                return;
            }
            update_status = 1;
            //服务器接口
            BaseGoods.get_all_len_skus().then(function (ret) {
                var all_len = ret[0].num;
                baison_app.api.showProgress({
                    text: '',
                    title: $rootScope.language.TIP_SETTING_UPLOAD_BUSY,
                    modal: false
                });
                update_batch_skus_price(0, all_len, 0);
            });
        };
        //同步结果保存
        var setSkuPrice_syn = function (result) {
            $scope.results.push(result);
            $api.setStorage('skuPrice', $scope.results);
        };
        //初始化
        var initSkuPrice_syn = function () {
            $scope.results = $api.getStorage('skuPrice') ? $api.getStorage('skuPrice') : [];
        };
        initSkuPrice_syn();
        //定时商品价格同步更新
        $scope.$on('skuPrcie', function (event, data) {
            var configData = $api.getStorage('configData');
            if (configData.skuPriceSynch.is_syn == 1) {
                return;
            }
            if (update_status == 1) {
                return;
            }
            update_status = 1;
            //服务器接口
            BaseGoods.get_all_len_skus().then(function (ret) {
                var all_len = ret[0].num;
                update_batch_skus_price(0, all_len, 0);
            }).catch(function (err) {
                $scope.$emit('no_skuPrcie', 'no');
            });
        });
    }];
//增值模块
var SettingIncrementModuleCtrl = ['$http', '$rootScope', '$scope', 'ngDialog', 'ShopSetCheck',
    function ($http,$rootScope, $scope, ngDialog, ShopSetCheck) {
        ShopSetCheck();
        $scope.curr = 'increment_module';
         $scope.incrementModule = {};
        //获取第三方模块的json
        $http.get('./thirdDev/thirdDev.json').success(function (ret) {
            $scope.incrementModule = ret;
        });
        $scope.module_state = false;
        var configData = $api.getStorage('configData');
        $scope.configData = configData;
        $scope.module_state =  configData.zftd==1?true:false;
        $scope.hzmodelclass = configData.zftd==1?'':'off';
        //盒子支付
        $scope.moduleSwitch = function () {
            var configData = $api.getStorage('configData');
            var systype = baison_app.api.systemType;
            $scope.module_state =  configData.zftd==1?true:false;
            if($rootScope.is_pc){
                baison_app.api.alert({msg:$rootScope.language.MSG_SORRY_NOT_IOS_CANT_USE});
                return;
            }else if(systype != 'ios'){
                baison_app.api.alert({msg:$rootScope.language.MSG_SORRY_NOT_IOS_CANT_USE});
                return;
            }
            if ($scope.module_state) {
                $scope.hzmodelclass = 'off';
                configData.zftd = 0;
            } else {
                $scope.hzmodelclass = '';
                configData.zftd = 1; 
                
            }
            $api.setStorage('configData', configData);
        }
        var configData = $api.getStorage('configData');
        //baison_app.api.alert({msg:configData.feifan.switched,title:'feifan'});
        
        $scope.ffmodelclass = configData.feifan.switched ? '': 'off';
        //baison_app.api.alert({msg:$scope.ffmodelclass,title:'feifan1'});
        //飞凡设备开关
        $scope.moduleSwitch1 = function () {
            var configData = $api.getStorage('configData');
            $scope.configData.feifan.switched = configData.feifan.switched;
            if (!configData.feifan.switched) {
                if(baison_app.api.systemType!='android'){
                    baison_app.api.alert({msg:$rootScope.language.TIPS_SYSTEM_NOT_SUPPORT});
                    return;
                }
                configData.feifan.switched = true;
                $scope.ffmodelclass = '';
            } else {
                configData.feifan.switched = false;
                $scope.ffmodelclass = 'off';
                configData.checklist.forEach(function (n,i) {//关闭时同时关闭该支付方式
                    if(n=='103'){
                        configData.checklist.splice(i,1);
                    }
                });
            }
            //baison_app.api.alert({msg:$scope.ffmodelclass,title:'feifan2'});
            //baison_app.api.alert({msg:configData.feifan.switched,title:'save'});
            $api.setStorage('configData', configData);
            //baison_app.api.alert({msg:$api.getStorage('configData').feifan.switched,title:'saveafter'});
            
        };
        
        


    }];
//测试页
var TestIndexCtrl = ['$scope', '$rootScope', 'dbSelect', 'dbReplace', 'dbUpdate', 'dbExec', 'dbInsertMulti', 'purviewInitial', '$location',
    function ($scope, $rootScope, dbSelect, dbReplace, dbUpdate, dbExec, dbInsertMulti, purviewInitial, $location) {
        var cate = 'C02';
        var sort = 'C02';  //count(*) num
        var GoodsCode = 'QX1001';
		//$scope.sql = 'select * from PosCategory limit 50';
		//$scope.sql = 'select * from PosGoods where  CategoryCode="' + cate + '" and  SortCode = "'+sort+'"';
        //$scope.sql = 'select * from PosSku where  GoodsCode="' + GoodsCode + '"';
		$scope.sql = "";
		$scope.curr = 'test';
		
        $scope.execsql = function () {
            var sql = $scope.sql;
            dbSelect('YsPos', sql).then(function (ret) {
                baison_app.api.alert({msg: ret});
                console.log(ret);
            }).catch(function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                    msg: err
                });
            });
        };
        data = {
            'is_upload': 0
        };
        $scope.getMyPurview = function () {
            $scope.myPurview = $rootScope.purview;
        }
        $scope.open_dev = function () {
            const BrowserWindow = nodeRequire('electron').remote.BrowserWindow;
            BrowserWindow.getFocusedWindow().webContents.openDevTools();
        };
        $scope.getAllPurview = function () {
            purviewInitial('purview').then(function (ret) {
                $rootScope.purview = ret.data;
//                if ($rootScope.user.UserCode == '000') {
                for (var x in $rootScope.purview) {
                    $rootScope.purview[x].show = 1;
                }
//                }
            });

        };
        $scope.goto_index = function () {
            $location.path('/index');
        };
        $scope.claar_local = function () {
            //PC 版本清空本地存储的配置文件，用于调试
            window.localStorage.clear();
        };
        //生成测试数据
        $scope.test_data = function () {
            return dbExec('YsPos', "update PosSku set SkuNum = 10 where GoodsCode in ('115209677','115303588','115309225','115309682','115319669','115421568','115421688','130309798','132126285','189050250','214419760','215209531','215209534','215303537','215326118','215350032','215421666','215421668')").then(function (ret) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT,
                    msg: ret
                });
            });
        };
        //城市选择器
        $scope.test_city = function () {
            baison_app.citySelector.open({}, function (ret) {
                console.log(ret);
            });
        }

        //监听扫描枪输入 =============================================================
        $scope.saomiaoSwitch = false;
        $scope.saomiaoStart = 0;
        $scope.saomiaoEnd = 0;
        $scope.saomiaoInput = '';
        $scope.saomiaoTimer = null;
        $rootScope.saomiao = function (event) {
            //console.log(event.keyCode);
            if ($scope.saomiaoTimer) {
                clearTimeout($scope.saomiaoTimer);
            }
            //开启扫描并记录扫描开始时间
            if (!$scope.saomiaoSwitch) {
                $scope.saomiaoStart = new Date().getTime();
                $scope.saomiaoInput = '';
            }
            $scope.saomiaoSwitch = true;
            $scope.saomiaoInput = $scope.saomiaoInput + String.fromCharCode(event.keyCode);

            $scope.saomiaoTimer = setTimeout(function () {
                $scope.saomiaoSwitch = false;
                $scope.saomiaoEnd = new Date().getTime();
                baison_app.api.toast({msg: $scope.saomiaoEnd - $scope.saomiaoStart});
                //3位以上且300毫秒以内认为是扫描枪录入
                if ($scope.saomiaoInput.length > 3 && ($scope.saomiaoEnd - $scope.saomiaoStart) < 800) {
                    $scope.saomiaoHandler($scope.saomiaoInput);
                    $scope.saomiaoInput = '';
                }
            }, 500);
        };

        $scope.saomiaoHandler = function (input_saomiao) {
            //baison_app.api.toast({msg:input_saomiao});
        };
        //============================================================================
    }
];
var getLocalIp = function () {
    var os = nodeRequire('os');
    var ifaces = os.networkInterfaces();
    var ip = [];
    Object.keys(ifaces).forEach(function (ifname) {
        var alias = 0;
        ifaces[ifname].forEach(function (iface) {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
                return;
            }

            if (alias >= 1) {
                // this single interface has multiple ipv4 addresses
                //console.log(ifname + ':' + alias, iface.address);
                ip.push(iface.address);
            } else {
                // this interface has only one ipv4 adress
                //console.log(ifname, iface.address);
                ip.push(iface.address);
            }
            ++alias;
        });
    });
    return ip;
};

//控制器
var SettingTaskCtrl = ['$scope', '$rootScope','Task','ShopSetCheck',
    function ($scope, $rootScope, Task,ShopSetCheck) {
        $scope.curr = 'task_by_time';
        ShopSetCheck();
        Task.get_task_name().then(function (response) {
            //存放时间频率
            $scope.taskFrequency = [
                {'frequency': 1, 'frequencySize': '30分钟'},
                {'frequency': 2, 'frequencySize': '1小时'},
                {'frequency': 3, 'frequencySize': '6小时'},
                {'frequency': 4, 'frequencySize': '12小时'},
                {'frequency': 5, 'frequencySize': '24小时'}
            ];
            $scope.taskContents = response;
            //增加一个标志位表示开启还是关闭
            $scope.taskContents.forEach(function (n, i) {

                if (n.off_or_on == 1) {
                    n.flag = true;
                } else {
                    n.flag = false;
                }
                if (n.start_time == null || n.start_time == undefined || isNaN(n.start_time)) {
                    n.start_time = new Date();
                } else {
                    n.start_time = new Date(Number(n.start_time))
                }
                if (n.end_time == null || n.end_time == undefined || isNaN(n.end_time)) {
                    n.end_time = new Date();
                } else {
                    n.end_time = new Date(Number(n.end_time));
                }

                switch (n.frequency) {
                    case '1800':
                        $scope.taskContents[i].frequency = 1;
                        break;
                    case '3600':
                        $scope.taskContents[i].frequency = 2;
                        break;
                    case '21600':
                        $scope.taskContents[i].frequency = 3;
                        break;
                    case '43200':
                        $scope.taskContents[i].frequency = 4;
                        break;
                    case '86400':
                        $scope.taskContents[i].frequency = 5;
                        break;
                }
            });
            $scope.task_code = $scope.taskContents[0].code;
        }).catch(function (err) {
        });
        $scope.save = function (data) {
            var _array = [];
            data.forEach(function (n, i) {
                var param = {};
                param.off_or_on = (data[i].flag == true) ? 1 : 0;
                param.frequency = data[i].frequency;
                if (isNaN(data[i].start_time) || data[i].start_time == undefined || data[i].start_time == null) {
                    param.start_time = new Date().getTime();
                } else {
                    param.start_time = new Date(data[i].start_time).getTime();//- 8 * 3600 + 365 * 10 * 3600 * 24
                }
                if (isNaN(data[i].end_time) || data[i].end_time == null || data[i].end_time == undefined) {
                    param.end_time = new Date().getTime();
                } else {
                    param.end_time = new Date(data[i].end_time).getTime();
                }


                param.start_time = (isNaN(data[i].start_time) || data[i].start_time == undefined || data[i].start_time == null) ? '' : new Date(data[i].start_time).getTime();
                param.end_time = (isNaN(data[i].end_time) || data[i].end_time == null || data[i].end_time == undefined) ? '' : new Date(data[i].end_time).getTime();
                param.code = data[i].code;
                _array.push(param);
            });
            Task.update_task_status(_array).then(function (response) {
                baison_app.api.toast({msg: '保存成功'});
            });
        };
        //同步结果
        var setKuCun_syn = function (result) {
            $scope.results.push(result);
            $api.setStorage('record', $scope.results);
        };
        //初始化
        var initKucun_syn = function () {
            $scope.results = $api.getStorage('record') ? $api.getStorage('record') : [];
        };
        initKucun_syn();
        //立即同步
        $scope.download = function (task) {
            var method = eval('Task.' + task.method);
            var param = {};
            param.code = task.code;
            //执行中
            param.status = 2;
            param.update_time = task.update_time;
            Task.update_status_by_sys_task(param).then(function (res) {
                //4.取url调用接口：url
                baison_app.api.showProgress({title: '正在下载，请稍候...'});
                method().then(function () {
                    baison_app.api.hideProgress();
                    baison_app.api.toast({msg: '下载成功'});
                    //5.调用成功后需要回写更新时间：update_time和状态: 1 正常  ,并且把结果存入数据
                    param.status = 1;
                    param.update_time = Math.ceil(new Date().getTime() / 1000);
                    Task.update_status_by_sys_task(param).then(function () {
                    });
                    var result = {
                        'syn': 0, //表示成功
                        'time': new Date(), //timeStamp2String(new Date(), 'datetime'),
                        'record_type': task.task_name,
                    };
                    setKuCun_syn(result);
                });
            });
        };
    }];
SettingTaskCtrl.$injector = ['$scope', '$rootScope',  'Task','ShopSetCheck'];
SettingNavCtrl.$injector = ['$scope', '$rootScope'];
SettingAboutCtrl.$injector = ['$scope', '$rootScope', '$location', '$http', 'ShopSetCheck', 'BaseGoods'];
SettingShopsetCtrl.$injector = ['$scope', '$rootScope', '$location', 'ShopGet', 'ShopSet', 'ShopSearch'];
SettingCashCtrl.$injector = ['$scope', '$rootScope', 'ngDialog', '$location', 'shopCashDesk'];
SettingChecksetCtrl.$injector = ['$scope', '$rootScope', 'checkGetList', 'ngDialog'];
SettingUsermanageCtrl.$injector = ['$rootScope', '$scope', 'PosUser', 'ngDialog', 'ShopSetCheck'];
SettingUsermanage2Ctrl.$injector = ['$scope', '$rootScope', 'ngDialog', 'PosUser', 'ShopSetCheck'];
SettingCommonsetCtrl.$injector = ['$scope', '$rootScope', 'LanguageSet', '$location', 'get_api', 'checkGetList'];
SettingPrintsetCtrl.$injector = ['$scope', '$rootScope', 'Print', 'timeStamp2String'];
SettingPatchCtrl.$injector = ['$rootScope', '$scope', 'PatchList', 'PatchDownload', 'ngDialog', 'ShopSetCheck'];
SettingWaituploadCtrl.$injector = ['$q', '$scope', '$rootScope', 'waitUpLoad', '$location', 'panDian', 'dbDelete', 'ThirdDev','BaseGoods'];
SettingChenLieCtrl.$injector = ['$scope', '$rootScope', 'ngDialog', 'BaseGoods'];
SettingStockSynchCtrl.$injector = ['$scope', '$rootScope', '$location', '$interval', 'BaseGoods', 'ReceiptRecord', 'timeStamp2String', 'ThirdDev','printWaitMsg','closePrintWaitMsg'];
SettingSkuPriceSynchCtrl.$injector = ['$scope', '$rootScope', '$location', '$interval', '$q', 'BaseGoods', 'ReceiptRecord'];
SettingIncrementModuleCtrl.$injector = ['$http', '$rootScope', '$scope', 'ngDialog', 'ShopSetCheck'];
TestIndexCtrl.$injector = ['$scope', '$rootScope', 'dbSelect', 'dbReplace', 'dbUpdate', 'dbInsertMulti', 'dbInsert', 'purviewInitial', '$location'];
angular.module('baisonDirective', [])
        .directive('onSaomiao', function () {
            return {
                restrict: 'A',
                scope: {
                    func: '&onSaomiao'
                },
                link: function (scope, elem, attrs) {
                    elem.bind('keypress', scope.func);
                }
            };
        });
